package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.context.BaseContext;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    //登录
    public Admin login(Account account) {//登录
        String username = account.getUsername();

        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin == null) {//没有这个用户
            throw new CustomException("500", "账号不存在");
        }

        String password = account.getPassword();
        if (!dbAdmin.getPassword().equals(password)) {
            throw new CustomException("500", "账号或密码错误");
        }
        return dbAdmin;
    }


    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    public void updatePassword(Account account) {
        Integer id = account.getId();
        Admin admin = this.selectById(id);
        if (!admin.getPassword().equals(account.getPassword())) {
            throw new CustomException("500", "原密码错误");
        } else if (account.getNewPassword().equals(account.getPassword())) {
            throw new CustomException("500", "旧密码与新密码相同");
        } else if (!account.getNewPassword().equals(account.getConfirmPassword())) {
            throw new CustomException("500", "两次输入的密码不一致");
        }
        admin.setPassword(account.getNewPassword());
        this.update(admin);
    }

    private void update(Admin admin) {
        adminMapper.updateById(admin);
    }
}
